import 'dart:async';

import 'package:flutter_axrjc/datasource/network/api/UserApi.dart';
import 'package:flutter_axrjc/datasource/network/bean/Account.dart';
import 'package:flutter_axrjc/datasource/network/bean/EventBean.dart';
import 'package:flutter_axrjc/datasource/network/bean/UserBean.dart';
import 'package:flutter_axrjc/datasource/network/request/exp.dart';
import 'package:flutter_axrjc/main.dart';
import 'package:flutter_axrjc/page/splash/logic.dart';
import 'package:flutter_axrjc/routes.dart';
import 'package:flutter_axrjc/util/Util.dart';
import 'package:flutter_easyloading/flutter_easyloading.dart';
import 'package:get/get.dart';

import 'state.dart';

class LoginLogic extends GetxController {
  final LoginState state = LoginState();

  Timer? _timer;
  late FormType formType;

  Account? accountFromCache;
  @override
  void onInit() {
    super.onInit();
    formType = (Get.arguments as FormType?) ?? FormType.other;
    Util.getAccount().then((value) {
      accountFromCache = value;
      state.isCheck.value = accountFromCache?.lastSaveAccount ?? false;
      if (state.isCheck.value) {
        state.phone.value = accountFromCache?.phone ?? '';
        state.password.value = accountFromCache?.password ?? '';
      }
    });
  }

  void startTimer() {
    if (!state.isTimerActive.value) {
      state.isTimerActive.value = true;
      _timer = Timer.periodic(const Duration(seconds: 1), (timer) {
        if (state.countDown.value == 0) {
          state.countDown.value = 60;
          state.isTimerActive.value = false;
          state.buttonText.value = "获取验证码";
          _timer?.cancel();
        } else {
          state.countDown.value--;
          state.buttonText.value = "${state.countDown.value}s后重新获取";
        }
      });
    }
  }

  Future<void> sendSmsCode() async {
    if (state.isTimerActive.value) {
      EasyLoading.showToast("${state.countDown.value}s后可重新获取");
      return;
    }
    if (state.phone.value.isEmpty) {
      EasyLoading.showToast("请输入手机号");
      return;
    }
    try {
      await UserApi.sendCode(telPhone: state.phone.value);
      startTimer();
    } catch (e) {
      print(e);
    }
  }

  Future<void> next() async {
    if (state.phone.value.isEmpty) {
      EasyLoading.showToast("请输入手机号");
      return;
    }
    if (state.type.value == 0) {
      if (state.password.value.isEmpty) {
        EasyLoading.showToast("请输入密码");
        return;
      }

      try {
        UserBean? user = await UserApi.login(
            phone: state.phone.value, password: state.password.value);
        await checkSavePassword();
        eventBus.fire(EventBean(type: EventType.refreshMyLights, data: null));
        eventBus.fire(EventBean(type: EventType.refreshProfile, data: null));
        if (user != null) {
          if (formType == FormType.splash) {
            Get.offNamed(MainRoutes.main);
          } else {
            EasyLoading.dismiss();
            Get.back(result: user);
          }
        } else {
          EasyLoading.showToast("登录失败");
        }
      } on ApiException catch (e) {
        EasyLoading.showToast(e.message);
      } catch (e) {
        print(e);
        EasyLoading.showToast("登录失败$e");
      }
      //登录
    } else {
      // 注册
      if (state.yzm.value.isEmpty) {
        EasyLoading.showToast("请输入验证码");
        return;
      }
      if (state.password.value.isEmpty) {
        EasyLoading.showToast("请输入密码");
        return;
      }
      if (!Util.isPassword(state.password.value)) {
        EasyLoading.showToast("密码为6到12位字母和数字组合");
        return;
      }
      try {
        UserBean? user = await UserApi.register(
            phone: state.phone.value,
            yzm: state.yzm.value,
            password: state.password.value);
        eventBus.fire(EventBean(type: EventType.refreshMyLights, data: null));
        eventBus.fire(EventBean(type: EventType.refreshProfile, data: null));
        if (user != null) {
          Get.back(result: true);
        } else {
          EasyLoading.showToast("注册失败");
        }
      } on ApiException catch (e) {
        EasyLoading.showToast(e.message);
      } catch (e) {
        EasyLoading.showToast("注册失败$e");
      }
    }
  }

  @override
  void onClose() {
    super.onClose();
    EasyLoading.dismiss();
    _timer?.cancel();
  }

  Future<void> checkSavePassword() async {
    if (state.isCheck.value) {
      await Util.saveAccount(Account(
          phone: state.phone.value,
          password: state.password.value,
          lastSaveAccount: state.isCheck.value));
    } else {
      await Util.saveAccount(
          Account(phone: "", password: "", lastSaveAccount: false));
    }
  }
}
